<?php

namespace IDock\Insurance\DEMO;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\DEMO\Request\AllDEMORequest;
use IDock\Insurance\DEMO\Response\AllDEMOResponse;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return $this->config;
    }

    protected $config;

    protected $usercode;

    protected $password;

    public function execute(Request $request): Response
    {
        /*** @var AllDEMORequest $request */
        $request->loadConfig($this->config);

        $request->setRequestId(md5(uniqid()));

        $request->setHeaders([]);

        $request = $this->sign($request);

        $request->setPreParameter($request->generate());

        $request->setBizParam($this->generate($request));

        return $this->request($request);
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }


    public function sign(Request $request): Request
    {
        return $request;
    }

    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /*** @var AllDEMORequest $request */
        /*** @var AllDEMOResponse $response */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        $isTestResponse = $GLOBALS['testResponse'] ?? '';

        if (!$isTestResponse) {
            $request->responseAfterLogs($response->getBody(), $response->isSuccess());
        }

        if ($response->isSuccess()) {

            if (!$this->decrypt($response)) {
                return $response;
            }

            if (!$isTestResponse) {
                $request->decryptLogs($request->getRequestId(), $response->getBody());
            }

            $response->printerInit();
        }


        return $response;
    }

    /**
     * 数据加密
     * @param Request $request
     * @return bool
     */
    public function encrypt(Request $request): bool
    {
        return true;
    }

    public function decrypt(AllDEMOResponse $response): bool
    {
        return true;
    }
}
